#include "foldercopier.h"
#include <iostream>

FolderCopier::FolderCopier(QObject *parent) :
    QObject(parent)
{
    totalSize= 0;
    totalSizeCopied = 0;
    _stoped = false;
}
void FolderCopier::setPathSource(QString &path)
{
    this->pathSource = QString(path);
}
void FolderCopier::setPathSource(const char *path)
{
    this->pathSource = QString(path);
}

void FolderCopier::setPathDest(QString &path)
{
    this->pathDest = QString(path);
}
void FolderCopier::setPathDest(const char *path)
{
    this->pathDest = QString(path);
}
QString FolderCopier::getPathDest()
{
    return this->pathDest;
}

void FolderCopier::setDriveLetter(QString &letter)
{
    this->driveLetter = QString(letter);
}
void FolderCopier::setDriveLetter(const char *letter)
{
    this->driveLetter = QString(letter);
}

int FolderCopier::getProgress()
{
    if(totalSize!=0)
        return (int)(((double)totalSizeCopied/(double)totalSize)*100);
    else
        return 0;
}


void FolderCopier::startCopy()
{
    *myLog<<"FolderCopier::startCopy()";
    *myLog<<"this->pathDest"<<this->pathDest;
    *myLog<<"this->this->pathSource"<<this->pathSource;
    *myLog<<"this->driveLetter"<<this->driveLetter;
    _stoped = false;
    if(this->pathDest!=""&&this->pathSource!=""&&this->driveLetter!="")
    {
        this->totalSize = 0;
        this->totalSizeCopied = 0;
        this->calculateTotalSize(this->pathSource);
        this->copyFolders(this->pathSource);
        if(_stoped)
        {
            qDebug() << "FolderCopier::startCopy(): emit stopedCopy()";
            this->removeFolders(this->pathDest);
            totalSizeCopied = totalSize;
            emit stopedCopy();
            _stoped = false;
        }
        else
        {
            qDebug() << "FolderCopier::startCopy(): emit finishCopy()";
            emit finishCopy();
        }
    }
}
void FolderCopier::removeFolders(const QString &path)
{
   return;//ahora se borra desde afuera.
   qDebug()<<"FolderCopier::removeFolder()";
   QDir directory(path);
   foreach(const QFileInfo &info, directory.entryInfoList(QDir::Dirs))
   {
       if(info.isDir())
       {
           QString folderName = info.fileName();
           if(info.fileName()!="."&&info.fileName()!="..")
           {
               qDebug() << "folder: " << folderName;
               QString targetPath = path + "/" + folderName;
               this->removeFolders(targetPath);
           }

       }
   }
   qDebug() << "files:";
   foreach(const QFileInfo &info, directory.entryInfoList(QDir::Files))
   {
       if(info.isFile())
       {
           QFile file(path+"/"+info.fileName());
           if(file.remove())
           {
               qDebug() << "removed file: "<<path+"/"+info.fileName();
           }
           else
           {
               qDebug() << "error removing file: "<<path+"/"+info.fileName();
           }
       }
   }
   QDir parentDstDir(path);
   if (!parentDstDir.rmdir(path))
   {
       qDebug() << "Error removing folder: "<<path;
   }
}

void FolderCopier::stopCopy()
{
    qDebug() << "FolderCopier::stopCopy()";
    _stoped = true;
}

void FolderCopier::calculateTotalSize(const QString &path)
{
    *myLog<<"FolderCopier::calculateTotalSize(const QString &path) "<<path;

    *myLog<<"Directories "<<this->driveLetter+path<<"\n";
    QDir directory(this->driveLetter+path);
    *myLog<<"Directories "<<this->driveLetter+path<<"\n";
    foreach(const QFileInfo &info, directory.entryInfoList(QDir::Dirs))
    {
        *myLog<<"foreach\n";
        if(_stoped) break;

        if(info.isDir())
        {
            *myLog<<"isDir\n";
            QString folderName = info.fileName();
            *myLog<<"folder name "<<folderName<<"\n";
            if(info.fileName()!="."&&info.fileName()!="..")
            {
                QString sourcePath = path + "/" + folderName;
                this->calculateTotalSize(sourcePath);
            }

        }
    }
    foreach(const QFileInfo &info, directory.entryInfoList(QDir::Files))
    {
        if(_stoped) break;
        if(info.isFile())
        {
            this->totalSize+= info.size();
            qDebug() << "Adding: "<<info.size();
            qDebug() << "Total size: "<<this->totalSize;
            *myLog<< "Adding: "<<info.size();
            *myLog<<"Total size:"<<this->totalSize;
        }
    }
}

void FolderCopier::copyFolders(const QString &path)
{
    qDebug() << "Copying folder: " << this->driveLetter+path;
    *myLog << "Copying folder: " << this->driveLetter+path;

    QDir directory(this->driveLetter+path);
    foreach(const QFileInfo &info, directory.entryInfoList(QDir::Dirs))
    {        
        if(_stoped) break;
        if(info.isDir())
        {
            QString folderName = info.fileName();
            if(info.fileName()!="."&&info.fileName()!="..")
            {
                qDebug() << "folder: " << folderName;
                *myLog  << "folder: " << folderName;
                QString sourcePath = path + "/" + folderName;
                this->copyFolders(sourcePath);
            }

        }
    }
    QString destFolder=this->pathDest +"/"+ path;
    QDir parentDstDir(destFolder);
    if (!parentDstDir.mkpath(destFolder))
    {
        *myLog << "Error creating path: "<<destFolder;
        qDebug() << "Error creating path: "<<destFolder;
        return;
    }
    qDebug() << "files:";
    *myLog << "files:";
    qDebug() << "-----";
    foreach(const QFileInfo &info, directory.entryInfoList(QDir::Files))
    {
        if(_stoped) break;
        if(info.isFile())
        {
            this->copyFile(this->driveLetter+path+"/"+info.fileName(), destFolder+"/"+info.fileName());
            qDebug() << "file: " << this->driveLetter+path+info.fileName();
            qDebug() << "new file: " << destFolder+"/"+info.fileName();
            *myLog << "file: " << this->driveLetter+path+info.fileName();
            *myLog << "new file: " << destFolder+"/"+info.fileName();

        }
    }
}

void FolderCopier::copyFile(const QString &source,const QString &to)
{
    *myLog << "FolderCopier::copyFile(const QString &source,const QString &to)"<<source<<" "<<to;
    QFile sourceFile(source);
    QFile toFile(to);
    *myLog << "if(toFile.open(QIODevice::WriteOnly)&&sourceFile.open(QIODevice::ReadOnly))";
    if(toFile.open(QIODevice::WriteOnly)&&sourceFile.open(QIODevice::ReadOnly))
    {
        *myLog << "Open!!";
        char data[1024];
        qint64 copiedSize = 0;
        qint64 read = sourceFile.read(data,1024);
        qint64 index = 0;
        while(read>0)
        {
            if(_stoped) break;
            copiedSize += toFile.write(data,read); // write a byte
            index+=read;
            sourceFile.seek(index);
            toFile.seek(index);
            this->totalSizeCopied +=read;
            read = sourceFile.read(data,1024);
        }
        qDebug() << "Copied %" <<(int)(((double)this->totalSizeCopied/(double)this->totalSize)*100);
        *myLog << "Copied %" <<(int)(((double)this->totalSizeCopied/(double)this->totalSize)*100);
        toFile.close();
    }
    sourceFile.close();
}


void FolderCopier::onWrite( qint64 copied )
{
    qDebug() << "bytes copied : " << this->totalSizeCopied;
    qDebug() << "bytes copied " << (this->totalSizeCopied/this->totalSize)*100<<" %";
}
